package com.xsd.prc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Description: 分支合并框架
 * @Author: zhoufuzong
 * @Created: 2021-01-06 20:42:05
 * @Version: 1.1.0
 */

class MyTask extends RecursiveTask<Integer> {
    public static final Integer ADJUST_VALUE=10;
    private int start;
    private int end;
    private int result;

    public MyTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end-start)<ADJUST_VALUE){
            for (int i = start; i <=end ; i++) {
                result +=i;

            }
        }else {
            int middle = (end+start)/2;

            MyTask f1 = new MyTask(start,middle);
            f1.fork();
            MyTask f2 = new MyTask(middle,end);
            f2.fork();
            result  =f2.join() + f1.join();
        }

        return result;
    }
}

public class ForkJoinTaskDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(0,100);
        ForkJoinPool pool = new ForkJoinPool();

        ForkJoinTask<Integer> task = pool.submit(myTask);
        System.out.println(task.get());

        pool.shutdown();
    }
}
